<?php

defined('SYSPATH') or die('Access error!');

class Model_Trade_Comments extends Model
{

    /**
     * 通用的查询供求列表(包含分页。如果不需要分页在获取的数据中只要保留下标为list的数据)
     * @param type $where_sql
     * @param type $nums
     * @return type
     */
    public function get_comments_list($where_sql = '', $nums = 10)
    {
        if (Arr::validate_arr($where_sql))
        {
            $where_sql = $this->get_table_where('tc', $where_sql);
        }
        $where_sql .= " ORDER BY tc.id DESC";
        $sql = 'SELECT tc.*,u.username,u.avatar ' .
                'FROM ' . $this->table . ' AS tc ' .
                'LEFT JOIN ' . $this->db->get_table('user') . ' AS u ON u.id = tc.user_id ' . $where_sql;
        $data = $this->get_page_list($sql, $nums);
        $comments_temp = $data['list'];
        $comments = array();
        if (Arr::validate_arr($comments_temp))
        {
            foreach ($comments_temp as $value)
            {
                $value['avatar_path'] = Model::factory('user')->create_avatar_path($value['user_id'], $value['avatar']);
                $comments[] = $value;
            }
        }
        $data['list'] = $comments;
        return $data;
    }

    /**
     * 根据用户的id获取自己评论相关的供求
     * @param type $user_id
     * @param type $nums
     * @return type
     */
    public function get_comments_post($where_arr = array(), $nums = 10)
    {
        $where_sql = ' WHERE 1=1 ';
        if(isset($where_arr['user_id'])) {
            $where_sql .= ' AND tc.user_id='.$where_arr['user_id'];
        }
        
        if(isset($where_arr['post_type'])){
             $where_sql .= " AND tp.post_type='".$where_arr['post_type']."'";
        }
        $where_sql .= " ORDER BY tc.id DESC";
        $sql = 'SELECT distinct tp.id,tc.user_id,tp.name,tp.id,tp.limit_time,u.username,u.avatar ' .
                'FROM ' . $this->table . ' AS tc ' .
                'LEFT JOIN ' . $this->db->get_table('trade_post') . ' AS tp ON tp.id = tc.trade_id ' .
                'LEFT JOIN ' . $this->db->get_table('user') . ' AS u ON u.id = tp.user_id ' . $where_sql;
        $data = $this->get_page_list($sql, $nums);
        $comments_temp = $data['list'];
        $comments = array();
        if (Arr::validate_arr($comments_temp))
        {
            foreach ($comments_temp as $value)
            {
                $value['url'] = Model::factory('trade_post')->create_trade_detail_url($value['id']);
                $value['avatar_path'] = Model::factory('user')->create_avatar_path($value['user_id'], $value['avatar']);
                $comments[] = $value;
            }
        }
        $data['list'] = $comments;
        return $data;
    }

}